import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useVocabulary } from '@/contexts/VocabularyContext';
import type { Category, Difficulty } from '@/types/vocabulary';
import { BookOpen, Settings, HelpCircle, BarChart3, Plus, Trophy } from 'lucide-react';
import { toast } from 'sonner';
import StatsDialog from '@/components/stats/StatsDialog';

const HomePage: React.FC = () => {
  const navigate = useNavigate();
  const { settings, updateSettings, getWordsByCategory, gameStats, categoryStats, categories } = useVocabulary();
  const [selectedCategory, setSelectedCategory] = useState<Category>('全部类别');
  const [localSettings, setLocalSettings] = useState(settings);
  const [statsDialogOpen, setStatsDialogOpen] = useState(false);

  const handleSaveSettings = () => {
    updateSettings(localSettings);
    toast.success('设置已保存');
  };

  const handleGameStart = (mode: string) => {
    const words = getWordsByCategory(selectedCategory);
    if (words.length === 0) {
      toast.error('该类别没有可用的单词');
      return;
    }
    navigate(`/${mode}`, { state: { category: selectedCategory } });
  };

  const gameCards = [
    {
      id: 'matching',
      title: '单词配对',
      description: '翻转卡片，找出英文单词与中文释义的正确配对，挑战记忆力和反应速度。',
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/02ead76d-8806-4837-bb5c-807a6f28e74f.jpg',
      progress: '关卡 1/4',
      buttonColor: 'bg-indigo-600 hover:bg-indigo-700',
      titleColor: 'text-indigo-700',
    },
    {
      id: 'spelling',
      title: '拼写练习',
      description: '根据中文释义，正确拼写出英文单词，提高单词拼写能力和记忆准确度。',
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/d0c7150c-c7f7-4805-8670-5068e7339e36.jpg',
      progress: '关卡 1/4',
      buttonColor: 'bg-purple-600 hover:bg-purple-700',
      titleColor: 'text-purple-700',
    },
    {
      id: 'quiz',
      title: '快速测验',
      description: '在规定时间内快速选出正确答案，挑战你的词汇反应速度和正确率。',
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/c6957ece-57b9-4010-b4c3-afb32bdf94e9.jpg',
      progress: '关卡 1/4',
      buttonColor: 'bg-pink-600 hover:bg-pink-700',
      titleColor: 'text-pink-700',
    },
  ];

  return (
    <div className="min-h-screen bg-[#F5F7FA]">
      {/* Top Navigation */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="container mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                xmlnsXlink="http://www.w3.org/1999/xlink"
                width="24px"
                height="24px"
                viewBox="0 0 142 139"
                fill="none"
                preserveAspectRatio="xMidYMid meet"
                key="a9b2c532-08da-49c3-afe7-e991f581d095"
                className="w-6 h-6 text-indigo-600">
                <rect width="142" height="139" fill="url(#pattern0_1_898)" />
                <defs>
                  <pattern
                    id="pattern0_1_898"
                    patternContentUnits="objectBoundingBox"
                    width="1"
                    height="1">
                    <use xlinkHref="#image0_1_898" transform="scale(0.00704225 0.00719424)" />
                  </pattern>
                  <image
                    id="image0_1_898"
                    width="142"
                    height="139"
                    preserveAspectRatio="none"
                    xlinkHref="" />
                </defs>
              </svg>
              <span className="text-xl font-semibold text-[#4b41f7ff]">WordMaster</span>
            </div>
            <div className="flex items-center gap-3">
              <Dialog>
                <DialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="rounded-full">
                    <HelpCircle className="w-5 h-5 text-gray-600" />
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
                  <DialogHeader>
                    <DialogTitle>游戏说明</DialogTitle>
                    <DialogDescription>了解如何玩转三种游戏模式</DialogDescription>
                  </DialogHeader>
                  <div className="space-y-6 mt-4">
                    <div>
                      <h3 className="font-semibold text-lg mb-2 text-indigo-700">单词配对</h3>
                      <p className="text-gray-600">
                        点击卡片翻转查看内容，找到英文单词和对应中文释义的配对。正确配对的卡片会保持翻转状态，错误配对会自动翻回。完成所有配对后查看用时和得分。
                      </p>
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg mb-2 text-purple-700">拼写练习</h3>
                      <p className="text-gray-600">
                        根据显示的中文释义，在输入框中输入正确的英文单词。点击检查按钮验证答案，系统会给出即时反馈。完成所有单词后查看正确率和错误单词列表。
                      </p>
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg mb-2 text-pink-700">快速测验</h3>
                      <p className="text-gray-600">
                        在限定时间内从四个选项中选择正确答案。题型包括英译中和中译英两种。回答速度越快得分越高，超时自动标记为错误。完成测验后查看总分和准确率。
                      </p>
                    </div>
                  </div>
                </DialogContent>
              </Dialog>

              <Dialog>
                <DialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="rounded-full">
                    <Settings className="w-5 h-5 text-gray-600" />
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>游戏设置</DialogTitle>
                    <DialogDescription>自定义您的游戏体验</DialogDescription>
                  </DialogHeader>
                  <div className="space-y-6 mt-4">
                    <div className="space-y-2">
                      <Label>游戏难度</Label>
                      <Select
                        value={localSettings.difficulty}
                        onValueChange={(value: Difficulty) =>
                          setLocalSettings({ ...localSettings, difficulty: value })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="easy">简单 (5个单词)</SelectItem>
                          <SelectItem value="medium">中等 (7个单词)</SelectItem>
                          <SelectItem value="hard">困难 (10个单词)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>测验时间限制</Label>
                      <Select
                        value={localSettings.timeLimit.toString()}
                        onValueChange={(value) =>
                          setLocalSettings({ ...localSettings, timeLimit: Number.parseInt(value) })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="10">10秒</SelectItem>
                          <SelectItem value="15">15秒</SelectItem>
                          <SelectItem value="20">20秒</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <Button onClick={handleSaveSettings} className="w-full">
                      保存设置
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>

              <Button variant="ghost" size="icon" className="rounded-full" onClick={() => setStatsDialogOpen(true)}>
                <BarChart3 className="w-5 h-5 text-gray-600" />
              </Button>
            </div>
          </div>
        </div>
      </header>
      {/* Stats Dialog */}
      <StatsDialog
        open={statsDialogOpen}
        onOpenChange={setStatsDialogOpen}
        gameStats={gameStats}
        categoryStats={categoryStats}
      />
      {/* Main Content */}
      <main className="container mx-auto px-6 py-12 max-w-6xl">
        {/* Hero Section */}
        <div className="text-center mb-12">
          <div className="flex justify-center mb-6">
            <div className="w-24 h-24 bg-white rounded-2xl shadow-lg flex items-center justify-center">
              <img
                src="https://miaoda-edit-image.cdn.bcebos.com/6ziaj75dcq2p/IMG-72mbhxld6ku9.png"
                alt="WordMaster Logo"
                className="w-20 h-20 object-contain"
                data-editor-config="%7B%22defaultSrc%22%3A%22https%3A%2F%2Fmiaoda-edit-image.cdn.bcebos.com%2F6ziaj75dcq2p%2FIMG-72mbhxld6ku8.png%22%7D" />
            </div>
          </div>
          <h1 className="text-4xl font-bold text-indigo-600 mb-3">词汇记忆挑战</h1>
          <p className="text-gray-600 text-lg">
            通过有趣的游戏模式，轻松掌握英语词汇，让学习变得更加高效和愉快！
          </p>
        </div>

        {/* Category Selection */}
        <div className="mb-10">
          <h2 className="text-center text-lg font-medium text-gray-700 mb-4">选择词汇类别</h2>
          <div className="flex flex-wrap justify-center gap-3">
            {categories.map((category) => (
              <button
                key={category}
                onClick={() => setSelectedCategory(category)}
                className={`px-6 py-2 rounded-full text-sm font-medium transition-all ${
                  selectedCategory === category
                    ? 'bg-indigo-600 text-white shadow-md'
                    : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-200'
                }`}
              >
                {category}
              </button>
            ))}
          </div>
        </div>

        {/* Game Cards */}
        <div className="grid md:grid-cols-3 gap-6 mb-10">
          {gameCards.map((card) => (
            <div
              key={card.id}
              className="bg-white rounded-2xl shadow-sm hover:shadow-lg transition-shadow overflow-hidden"
            >
              <div className="relative h-48 overflow-hidden">
                <img src={card.image} alt={card.title} className="w-full h-full object-cover" />
              </div>
              <div className="p-6">
                <h3 className={`text-xl font-bold mb-2 ${card.titleColor}`}>{card.title}</h3>
                <p className="text-gray-600 text-sm mb-4 leading-relaxed">{card.description}</p>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-gray-500">{card.progress}</span>
                  <Button
                    onClick={() => handleGameStart(card.id)}
                    className={`${card.buttonColor} text-white px-6`}
                  >
                    开始游戏
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Bottom Actions */}
        <div className="flex justify-center gap-4">
          <Button
            variant="outline"
            onClick={() => navigate('/vocabulary')}
            className="border-gray-300"
          >
            <BarChart3 className="w-4 h-4 mr-2" />
            查看完整词汇表
          </Button>

          <Button
            variant="outline"
            onClick={() => navigate('/achievements')}
            className="border-purple-300 text-purple-600 hover:bg-purple-50"
          >
            <Trophy className="w-4 h-4 mr-2" />
            成就系统
          </Button>
        </div>
      </main>
    </div>
  );
};

export default HomePage;
